package com.woniuxy.log;

import com.woniuxy.daos.TbLogDao;
import com.woniuxy.entitys.TbLog;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 记录日志
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private TbLogDao tbLogDao;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 给标注了LogAnnotation注解的方法切入
     */
    @Pointcut(value = "@annotation(com.woniuxy.log.LogAnnotation)")
    public void myPointcut(){}

    /**
     * 后置通知
     * @param joinPoint
     */
    @AfterReturning("myPointcut()")
    public void afterExecute(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        if(annotation != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader("token");
            String phone = jwtUtils.getUsername(token);
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("user:" + phone);
            String info = annotation.info();
            TbLog tbLog = new TbLog();
            tbLog.setUid(loginUser.getUser().getUid());
            tbLog.setContext(info);
            tbLog.setLogIp(request.getRemoteAddr());
            tbLog.setLogTime(new Date());
            tbLogDao.insert(tbLog);
        }
    }
}
